package com.yuan.base.service.common;

import java.util.Collections;
import java.util.HashMap;
import java.util.Map;

/**
 * 上下文
 *
 * @author lintiangang
 * @date 2021/03/25 17:03
 **/
public class BaseContext {

    /**
     * 上下文
     */
    private final static ThreadLocal<Map<String, Object>> requestContext = new ThreadLocal<>();

    public static void put(String name, Object value) {
        Map<String, Object> contextMap = initRequestContext();
        contextMap.put(name, value);
    }

    public static Object get(String name) {
        Map<String, Object> contextMap = initRequestContext();
        return contextMap.get(name);
    }

    public static Object remove(String name) {
        Map<String, Object> contextMap = initRequestContext();
        Object result = contextMap.get(name);
        contextMap.remove(name);
        return result;
    }

    public static void clean() {
        //线程是有限的，所以不直接 ThreadLocal remove，而是清空map
        Map<String, Object> contextMap = initRequestContext();
        contextMap.clear();
    }

    private static Map<String, Object> initRequestContext() {
        Map<String, Object> contextMap = requestContext.get();

        if (contextMap == null) {
            synchronized (requestContext) {
                contextMap = requestContext.get();
                if (contextMap != null) {
                    return contextMap;
                }

                contextMap = Collections.synchronizedMap(new HashMap<String, Object>());
                requestContext.set(contextMap);
            }
        }
        return contextMap;
    }
}
